package com.example.administrator.text;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import app.BaseActivity;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import util.AndroidJSInterface;
import util.HomeUtil;
import util.LogUtil;

public class WebshipActivity extends BaseActivity{
    private Boolean islandport = true;//true表示此时是竖屏，false表示此时横屏。
    private View xCustomView;
    private xWebChromeClient xwebchromeclient;
    private AudioManager mAudioManager;
    private String mString,stirnt;
    public static final String mWEB = "WEB";
    private WebChromeClient.CustomViewCallback 	xCustomViewCallback;

    private int count = 0;  //计算点击的次数
    private long firClick,secClick;//第一次点击的时间 long型
    private long lastClick;//最后一次点击的时间
    private int firstId;    //第一次点击的button的id
    //网页加载出错进显示页面
    //网页加载出错正在刷新
    private TextView videorefresh;
    private IntentFilter mIntentFilter;
    private onDoubleClick listClick = new onDoubleClick();
    private GestureDetector gestureScanner;
    @Bind(R.id.seekBar_webship)     ProgressBar mProgressBar;    //进度条
    @Bind(R.id.video_error)         TextView    videoerror;
    @Bind(R.id.text_shiping)        TextView    mTextView;
    @Bind(R.id.video_view)          FrameLayout videoview;     // 全屏时视频加载view
    @Bind(R.id.feedback_frame_ship) FrameLayout mFrameLayout;
    @Bind(R.id.video_webview)       WebView     videowebview;

    @Override protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webship);
        mString = getIntent().getStringExtra("stringurl");
        stirnt = getIntent().getStringExtra("stringtitle");
        ButterKnife.bind(this);
        initwidget();
        LogUtil.eE("",stirnt);
        videowebview.loadUrl(mString);
    }

    @OnClick(R.id.image_feedbck_ship) void imaget(){
        videowebview.loadUrl("about:blank");
        videowebview.onPause();
        finish();
    }

    @SuppressWarnings("deprecation")
    private void initwidget() {

        mIntentFilter = new IntentFilter();
        mIntentFilter.addAction(mWEB);
        registerReceiver(broadcastReceiver,mIntentFilter);
        videoview.setOnTouchListener(listClick);
        mTextView.setText(stirnt);
        videorefresh = (TextView) findViewById(R.id.video_refresh);
        xwebchromeclient = new xWebChromeClient();
        videowebview.setWebChromeClient(xwebchromeclient);
        videowebview.setWebViewClient(new xWebViewClientent());
        AndroidJSInterface ajsi = new AndroidJSInterface(this);
        videowebview.addJavascriptInterface(ajsi,ajsi.getInterface());
        videoerror.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                LogUtil.eE("WebView","setOnClickListener"+arg0);
                videowebview.loadUrl("about:blank");
                videowebview.loadUrl(mString);
                videoerror.setVisibility(View.GONE);
                videorefresh.setVisibility(View.VISIBLE);
                videowebview.setVisibility(View.GONE);
            }
        });

        WebSettings ws = videowebview.getSettings();
        HomeUtil.getHemeUtilNew().getStatusBar(this,mFrameLayout);

        /**
         * setAllowFileAccess 启用或禁止WebView访问文件数据 setBlockNetworkImage 是否显示网络图像
         * setBuiltInZoomControls 设置是否支持缩放 setCacheMode 设置缓冲的模式
         * setDefaultFontSize 设置默认的字体大小 setDefaultTextEncodingName 设置在解码时使用的默认编码
         * setFixedFontFamily 设置固定使用的字体 setJavaSciptEnabled 设置是否支持Javascript
         * setLayoutAlgorithm 设置布局方式 setLightTouchEnabled 设置用鼠标激活被选项
         * setSupportZoom 设置是否支持变焦
         * */
        ws.setBuiltInZoomControls(true);// 隐藏缩放按钮
        ws.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);// 排版适应屏幕
        ws.setUseWideViewPort(true);// 可任意比例缩放
        ws.setLoadWithOverviewMode(true);// setUseWideViewPort方法设置webview推荐使用的窗口。setLoadWithOverviewMode方法是设置webview加载的页面的模式。
        ws.setSavePassword(true);
        ws.setUseWideViewPort(true);
        ws.setSaveFormData(true);// 保存表单数据
        ws.setJavaScriptEnabled(true);
        ws.setDisplayZoomControls(false);         //隐藏webview缩放按钮
        ws.setGeolocationEnabled(true);// 启用地理定位
        ws.setGeolocationDatabasePath("/data/data/org.itri.html5webview/databases/");// 设置定位的数据库路径
        ws.setDomStorageEnabled(true);


    }
    /**
     *创建一个动态广播
     */
    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override public void onReceive(Context context, Intent intent) {
             String string = intent.getStringExtra("jsjava");
             if(string.equals("huen")){
                 mFrameLayout.setVisibility(View.GONE);
             }else {
                 mFrameLayout.setVisibility(View.VISIBLE);
             }

        }
    };

    @Override public boolean onKeyDown(int keyCode, KeyEvent event) {

        if(mAudioManager == null){mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);}
        switch (keyCode){
            case  KeyEvent.KEYCODE_VOLUME_DOWN:
                mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,AudioManager.ADJUST_LOWER,
                        AudioManager.FX_FOCUS_NAVIGATION_UP);//音量-
                break;
            case KeyEvent.KEYCODE_VOLUME_UP:
                mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,AudioManager.ADJUST_RAISE,
                        AudioManager.FX_FOCUS_NAVIGATION_UP);//音量+
                break;
            case KeyEvent.KEYCODE_BACK:
                 if (inCustomView()) {
                    hideCustomView();
                    return true;
                 }

                 if(videowebview.canGoBack()){
                     videowebview.goBack();
                 }else {
                     WebshipActivity.this.finish();
                 }
                break;
        }
        return true;
    }

    /**
     * 判断是否是全屏
     */
    public boolean inCustomView() {
        return (xCustomView != null);
    }

    /**
     * 全屏时按返加键执行退出全屏方法
     */
    public void hideCustomView() {
        xwebchromeclient.onHideCustomView();
    }

    /**
     * 处理Javascript的对话框、网站图标、网站标题以及网页加载进度等
     */
    public class xWebChromeClient extends WebChromeClient {
        private Bitmap xdefaltvideo;
        private View xprogressvideo;
        @Override
        //播放网络视频时全屏会被调用的方法
        public void onShowCustomView(View view, CustomViewCallback callback)
        {
            if (islandport) {

            }
            else{

            }
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            videowebview.setVisibility(View.GONE);
            //如果一个视图已经存在，那么立刻终止并新建一个
            if (xCustomView != null) {
                callback.onCustomViewHidden();
                return;
            }
            videoview.addView(view);
            xCustomView = view;
            xCustomViewCallback = callback;
            mFrameLayout.setVisibility(View.GONE);
            videoview.setVisibility(View.VISIBLE);
            if(getRequestedOrientation()!=ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE){
                getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                        WindowManager.LayoutParams.FLAG_FULLSCREEN);
            }
        }

        @Override
        //视频播放退出全屏会被调用的
        public void onHideCustomView() {

            if (xCustomView == null)//不是全屏播放状态
                return;

            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            xCustomView.setVisibility(View.GONE);
            videoview.removeView(xCustomView);
            xCustomView = null;
            mFrameLayout.setVisibility(View.VISIBLE);
            videoview.setVisibility(View.GONE);
            xCustomViewCallback.onCustomViewHidden();
            videowebview.setVisibility(View.VISIBLE);
        }
        //视频加载添加默认图标
        @Override
        public Bitmap getDefaultVideoPoster() {
            if (xdefaltvideo == null) {
                xdefaltvideo = BitmapFactory.decodeResource(
                        getResources(), R.mipmap.videoicon);
            }
            return xdefaltvideo;
        }
        //视频加载时进程loading
        @Override
        public View getVideoLoadingProgressView() {
            //Log.i(LOGTAG, "here in on getVideoLoadingPregressView");

            if (xprogressvideo == null) {
                LayoutInflater inflater = LayoutInflater.from(WebshipActivity.this);
                xprogressvideo = inflater.inflate(R.layout.video_loading_progress, null);
            }
            return xprogressvideo;
        }
        //网页标题
        @Override public void onReceivedTitle(WebView view, String title) {
            (WebshipActivity.this).setTitle(title);
        }

        @Override public void onProgressChanged(WebView view, int newProgress) {
            if(newProgress == 100){
                mProgressBar.setVisibility(View.GONE);
            }else {

                mProgressBar.setVisibility(View.VISIBLE);
                mProgressBar.setProgress(newProgress);
            }
            super.onProgressChanged(view, newProgress);
        }
    }

    /**
     * 处理各种通知、请求等事件
     */
    public class xWebViewClientent extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return false;
        }


        @Override
        public void onReceivedError(WebView view, int errorCode,
                                    String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            // 这里进行无网络或错误处理，具体可以根据errorCode的值进行判断，做跟详细的处理。
            // view.loadUrl(file:///android_asset/error.html );

            videowebview.setVisibility(View.GONE);
            videoerror.setVisibility(View.VISIBLE);
            videorefresh.setVisibility(View.GONE);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            videowebview.setVisibility(View.VISIBLE);
            videoerror.setVisibility(View.GONE);
            videorefresh.setVisibility(View.GONE);
            super.onPageFinished(view, url);
        }
    }
    /**
     * 当横竖屏切换时会调用该方法
     * @author
     */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE){
            mFrameLayout.setVisibility(View.GONE);
            islandport = false;
        }else if(newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
            mFrameLayout.setVisibility(View.VISIBLE);
            islandport = true;
        }
    }
    class onDoubleClick implements View.OnTouchListener{
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if(MotionEvent.ACTION_DOWN == event.getAction()){
                count++;
                if(count == 1){
                    firClick = System.currentTimeMillis();

                } else if (count == 2){
                    secClick = System.currentTimeMillis();
                    if(secClick - firClick < 500){
                        //双击事件
                    }
                    else {
                    }
                    count = 0;
                    firClick = 0;
                    secClick = 0;
                }
            }
            return true;
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(broadcastReceiver !=null){
            unregisterReceiver(broadcastReceiver);
        }
    }
}
